﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Ivory;
using Microsoft.Xna.Framework.Input;
using Schism.libs;

namespace Schism.Cameras
{
    public class Camera : IViewableController
    {
        //Fields
        private LevelBase _MapAssociation;
        public Vector2 CameraTopLeft;
        public Vector2 CameraViewport;

        public float ScrollSpeed = 5.67f;
        public bool Updated { get; set; }
        public bool EnableEdgeScrolling { get; set; }

        //Construct
        public Camera(LevelBase map)
        {
            this.Updated = true;
            this._MapAssociation = map;
            this.CameraViewport = new Vector2(ObjectHolder.GameObject.GraphicsDevice.Viewport.Width, ObjectHolder.GameObject.GraphicsDevice.Viewport.Height); 
        }

        //Methods
        private void ClampToMap()
        {
            Rectangle boundingRect = new Rectangle(0, 0,
                _MapAssociation.WorldPixelWidth,
                _MapAssociation.WorldPixelHeight);

            CameraTopLeft.X = (float)MathHelper.Clamp(CameraTopLeft.X, 0, boundingRect.Width - CameraViewport.X);
            CameraTopLeft.Y = (float)MathHelper.Clamp(CameraTopLeft.Y, 0, boundingRect.Height - CameraViewport.Y);
        }

        public void Render(SpriteBatch batch, GameTime time)
        {
            return; //nothing todo here ...
        }
        public void Solve(InputControl control, GameTime time)
        {
            #region EdgeScrolling


            #endregion

            #region WSAD Movement
            Updated = false;
            Vector2 camMoveDirection = Vector2.Zero;

            if (control.IsKeyDown(Keys.W) || control.IsKeyDown(Keys.Up))
                camMoveDirection.Y = -1;
            else if (control.IsKeyDown(Keys.S) || control.IsKeyDown(Keys.Down))
                camMoveDirection.Y = 1;

            if (control.IsKeyDown(Keys.A) || control.IsKeyDown(Keys.Left))
                camMoveDirection.X = -1;
            else if (control.IsKeyDown(Keys.D) || control.IsKeyDown(Keys.Right))
                camMoveDirection.X = 1;

            if (camMoveDirection != Vector2.Zero)
            {
                camMoveDirection.Normalize();
                camMoveDirection *= ScrollSpeed;
                CameraTopLeft += camMoveDirection;
                ClampToMap();

                camMoveDirection = Vector2.Zero;
                Updated = true;
            }
            #endregion
        }

        public bool Initalize()
        {
            return true; 
        }
        public bool Load()
        {
            
            return true; 
        }

        private bool IsVisible()
        {
            return false;
        }
    }
}
